<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约编号" prop="appointmentNo">
        <el-input
          v-model="queryParams.appointmentNo"
          placeholder="请输入预约编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="鱼塘" prop="pondId">
        <pond-select v-model="queryParams.pondId" placeholder="请选择鱼塘" />
      </el-form-item>
      <el-form-item label="签到状态" prop="checkinStatus">
        <el-select v-model="queryParams.checkinStatus" placeholder="请选择签到状态" clearable>
          <el-option
            v-for="dict in pond_checkin_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约日期" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          :disabled="!hasCheckedIn"
          @click="handleBatchConfirm"
          v-hasPermi="['pond:order:confirmCheckin']"
        >批量确认签到</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pond:appointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="rowSelectable" />
      <el-table-column label="预约编号" align="center" prop="appointmentNo" width="120" />
      <el-table-column label="用户姓名" align="center" prop="userName" width="100" />
      <el-table-column label="手机号" align="center" prop="userPhone" width="120" />
      <el-table-column label="鱼塘" align="center" prop="pondName" width="100" />
      <el-table-column label="钓位" align="center" prop="seatName" width="80" />
      <el-table-column label="预约日期" align="center" prop="appointmentDate" width="100" />
      <el-table-column label="时间段" align="center" width="120">
        <template #default="scope">
          <span>{{ scope.row.startTime }} - {{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到状态" align="center" prop="checkinStatus" width="100">
        <template #default="scope">
          <dict-tag :options="pond_checkin_status" :value="scope.row.checkinStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="签到时间" align="center" prop="checkinTime" width="150">
        <template #default="scope">
          <span>{{ scope.row.checkinTime ? parseTime(scope.row.checkinTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="确认时间" align="center" prop="confirmTime" width="150">
        <template #default="scope">
          <span>{{ scope.row.confirmTime ? parseTime(scope.row.confirmTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button 
            v-if="scope.row.checkinStatus == 1"
            link 
            type="success" 
            icon="Check" 
            @click="handleConfirmCheckin(scope.row)" 
            v-hasPermi="['pond:order:confirmCheckin']"
          >确认签到</el-button>
          <el-button 
            v-if="scope.row.checkinStatus == 2 && scope.row.orderId"
            link 
            type="primary" 
            icon="View" 
            @click="handleViewOrder(scope.row)" 
            v-hasPermi="['pond:order:query']"
          >查看订单</el-button>
          <el-button 
            v-if="scope.row.checkinStatus == 0"
            link 
            type="info" 
            icon="Clock" 
            disabled
          >等待签到</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 确认签到对话框 -->
    <el-dialog title="确认签到" v-model="confirmDialog.visible" width="500px" append-to-body>
      <el-form :model="confirmDialog.form" label-width="100px">
        <el-form-item label="用户信息">
          <span>{{ confirmDialog.form.userName }} ({{ confirmDialog.form.userPhone }})</span>
        </el-form-item>
        <el-form-item label="鱼塘钓位">
          <span>{{ confirmDialog.form.pondName }} - {{ confirmDialog.form.seatName }}</span>
        </el-form-item>
        <el-form-item label="预约时间">
          <span>{{ confirmDialog.form.appointmentDate }} {{ confirmDialog.form.startTime }} - {{ confirmDialog.form.endTime }}</span>
        </el-form-item>
        <el-form-item label="签到时间">
          <span>{{ confirmDialog.form.checkinTime ? parseTime(confirmDialog.form.checkinTime, '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
        </el-form-item>
        <el-form-item label="鱼塘" prop="pondId">
          <pond-select v-model="confirmDialog.form.pondId" @change="handlePondChange" />
        </el-form-item>
        <el-form-item label="钓位" prop="seatId">
          <el-select v-model="confirmDialog.form.seatId" placeholder="请选择钓位">
            <el-option 
              v-for="seat in availableSeats" 
              :key="seat.id" 
              :label="seat.name" 
              :value="seat.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="confirmDialog.form.remark" type="textarea" rows="3" placeholder="请输入确认备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirmDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmCheckinSubmit">确认签到</el-button>
      </template>
    </el-dialog>

    <!-- 批量确认对话框 -->
    <el-dialog title="批量确认签到" v-model="batchConfirmDialog.visible" width="600px" append-to-body>
      <div class="batch-confirm-content">
        <p>确认要批量确认以下 {{ selectedAppointments.length }} 个预约的签到状态吗？</p>
        <el-table :data="selectedAppointments" style="margin-top: 20px;">
          <el-table-column prop="userName" label="用户姓名" width="100" />
          <el-table-column prop="userPhone" label="手机号" width="120" />
          <el-table-column prop="pondName" label="鱼塘" width="100" />
          <el-table-column prop="seatName" label="钓位" width="80" />
          <el-table-column prop="appointmentDate" label="预约日期" width="100" />
          <el-table-column label="时间段" width="120">
            <template #default="scope">
              <span>{{ scope.row.startTime }} - {{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="batchConfirmDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchConfirmSubmit">确认批量操作</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AppointmentEnhanced">
import { listAppointment, getAppointment, delAppointment, addAppointment, updateAppointment } from "@/api/pond/appointment";
import { confirmCheckin } from "@/api/pond/order";
import PondSelect from "@/components/PondSelect";

const { proxy } = getCurrentInstance();
const { pond_checkin_status } = proxy.useDict('pond_checkin_status');
const router = useRouter();

const appointmentList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const availableSeats = ref([]);
const selectedAppointments = ref([]);
const hasCheckedIn = ref(false);

const confirmDialog = reactive({
  visible: false,
  form: {}
});

const batchConfirmDialog = reactive({
  visible: false
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appointmentNo: null,
    userName: null,
    userPhone: null,
    pondId: null,
    checkinStatus: null,
  }
});

const { queryParams } = toRefs(data);

/** 查询预约列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != dateRange && '' != dateRange) {
    queryParams.value.params["beginTime"] = dateRange.value[0];
    queryParams.value.params["endTime"] = dateRange.value[1];
  }
  listAppointment(queryParams.value).then(response => {
    appointmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  selectedAppointments.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  hasCheckedIn.value = selection.some(item => item.checkinStatus == 1);
}

// 行选择判断
function rowSelectable(row) {
  return row.checkinStatus == 1; // 只有已签到的可以选择
}

/** 确认签到 */
function handleConfirmCheckin(row) {
  confirmDialog.form = {
    appointmentSegmentId: row.appointmentSegmentId,
    pondId: row.pondId,
    seatId: row.seatId,
    userName: row.userName,
    userPhone: row.userPhone,
    pondName: row.pondName,
    seatName: row.seatName,
    appointmentDate: row.appointmentDate,
    startTime: row.startTime,
    endTime: row.endTime,
    checkinTime: row.checkinTime,
    remark: null
  };
  confirmDialog.visible = true;
}

/** 提交确认签到 */
function handleConfirmCheckinSubmit() {
  const requestData = {
    appointmentSegmentId: confirmDialog.form.appointmentSegmentId,
    pondId: confirmDialog.form.pondId,
    seatId: confirmDialog.form.seatId,
    remark: confirmDialog.form.remark
  };
  
  confirmCheckin(requestData).then(response => {
    proxy.$modal.msgSuccess("确认签到成功，已生成订单");
    confirmDialog.visible = false;
    getList();
  }).catch(error => {
    proxy.$modal.msgError("确认签到失败：" + error.message);
  });
}

/** 批量确认签到 */
function handleBatchConfirm() {
  if (selectedAppointments.value.length === 0) {
    proxy.$modal.msgWarning("请选择要确认的预约记录");
    return;
  }
  batchConfirmDialog.visible = true;
}

/** 提交批量确认 */
function handleBatchConfirmSubmit() {
  const promises = selectedAppointments.value.map(appointment => {
    const requestData = {
      appointmentSegmentId: appointment.appointmentSegmentId,
      pondId: appointment.pondId,
      seatId: appointment.seatId,
      remark: '批量确认签到'
    };
    return confirmCheckin(requestData);
  });
  
  Promise.all(promises).then(() => {
    proxy.$modal.msgSuccess(`批量确认成功，共处理 ${selectedAppointments.value.length} 个预约`);
    batchConfirmDialog.visible = false;
    getList();
  }).catch(error => {
    proxy.$modal.msgError("批量确认失败：" + error.message);
  });
}

/** 查看订单 */
function handleViewOrder(row) {
  router.push({
    path: '/fish/order/detail',
    query: { orderId: row.orderId }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pond/appointment/export', {
    ...queryParams.value
  }, `appointment_${new Date().getTime()}.xlsx`)
}

/** 鱼塘变化时获取钓位列表 */
function handlePondChange(pondId) {
  if (pondId) {
    // 这里需要调用获取钓位列表的API
    // getSeatsByPondId(pondId).then(response => {
    //   availableSeats.value = response.data;
    // });
    availableSeats.value = []; // 临时处理
  } else {
    availableSeats.value = [];
  }
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.batch-confirm-content {
  max-height: 400px;
  overflow-y: auto;
}
</style>